package com.chookss.home.gallery;

import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.GalleryTagEntity;
import com.chookss.tools.GlideUtils;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.view.RecycleViewDivider;
import com.google.gson.reflect.TypeToken;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;

public class GallerySingleChoiceLabelActivity extends BaseAct {

    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.common_right_txt)
    TextView commonRightTxt;
    @BindView(R.id.rvView)
    RecyclerView rvView;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    private LabelAdapter adapter;
    private List<GalleryTagEntity> list = new ArrayList<>();
    private String tagName = "";
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_gallery_choice_label);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        ivNone.setBackgroundResource(R.drawable.icon_default_no_common);
        tvNone.setText("暂无标签");
        rvView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager
                .VERTICAL, false));
        rvView.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        adapter = new LabelAdapter(R.layout.item_gallery_choice_label, this, list);
        rvView.setAdapter(adapter);
        ((SimpleItemAnimator) rvView.getItemAnimator()).setSupportsChangeAnimations(false);
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        srlView.autoRefresh();
        edContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        tagName = v.getText().toString();
                        Utils.hideInputKeyboard(GallerySingleChoiceLabelActivity.this, edContent);
                        srlView.autoRefresh();
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入搜索标签");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });
        edContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (Utils.isNull(s.toString())) {
                    commonRightTxt.setText("取消");
                } else {
                    commonRightTxt.setText("搜索");
                }
            }
        });
    }

    private void getData() {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("pageNum", currentPage + "");
        allmap.put("pageSize", "40");
        if (!Utils.isNull(tagName)) {
            allmap.put("tagName", tagName);
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<GalleryTagEntity>>>() {
        }.getType(), null, Urls.getTagList, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<List<GalleryTagEntity>>() {
            @Override
            public void onSuccess(List<GalleryTagEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if (srlView == null || llNone == null) {
                    return;
                }
                int oldIndex = list.size();
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    if (data.size() < 40) {
                        isEnd = true;
                    }
                    if (currentPage == 1) {
                        adapter.notifyDataSetChanged();
                    } else {
                        adapter.notifyItemRangeChanged(oldIndex, data.size());
                    }
                    srlView.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        srlView.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }
                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @OnClick({R.id.common_title_back, R.id.common_right_txt})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_txt:
                if (commonRightTxt.getText().toString().equals("取消")) {
                    finish();
                } else {
                    tagName = edContent.getText().toString();
                    if (edContent != null) {
                        Utils.hideInputKeyboard(this, edContent);
                    }
                    srlView.autoRefresh();
                }
                break;
        }
    }

    class LabelAdapter extends BaseQuickAdapter<GalleryTagEntity, BaseViewHolderEx> {
        private Context context;

        public LabelAdapter(int layoutResId, Context context, @Nullable List<GalleryTagEntity> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, GalleryTagEntity item) {
            ImageView ivImage = helper.getView(R.id.ivImage);
            TextView tvTitle = helper.getView(R.id.tvTitle);
            TextView tvNum = helper.getView(R.id.tvNum);
            tvTitle.setText(item.getTagName() + "");
            tvNum.setText(item.getImageNum() + "");
            if(Utils.isNull(item.getImagePath())){
                Glide.with(context).load(R.drawable.iv_default_tag).transform(new RoundedCorners(Utils.dip2px(context,4))).into(ivImage);
            }else{
                GlideUtils.loadCustomRound(context, item.getImagePath(), ivImage, R.drawable.default_news,4);
            }

            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Map<String, String> map = new HashMap<>();
                    map.put("galleryTagName",item.getTagName());
                    map.put("galleryTagCode",item.getTagCode());
                    EventBus.getDefault().post(new MyEvent(map));
                    finish();
                }
            });
        }

    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh(true);
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (edContent != null) {
            Utils.hideInputKeyboard(this, edContent);
        }
    }
}
